# coding:utf-8
from BigDataWeb.algorithm import Algorithm
import matplotlib.pyplot as plt
from statsmodels.tsa.stattools import adfuller as ADF
from statsmodels.stats.diagnostic import acorr_ljungbox
import pandas as pd

'''
时间序列
'''


class TimeSeries(Algorithm):
    # 待分析数据(pd.Series)
    inputs = None
    # 时间字段
    time_field_name = ""
    # 值字段
    value_field_name = ""
    # 预测周期数(小时/日/月/年度/季度)
    forcast_period_cnt = 3
    # 平稳性检测结果
    adf_check_result = []
    # 白噪声(white noise)检测结果
    wn_check_result = []
    # 差分阶数
    diff_degrees = 0
    # 预测结果
    forcast_reuslt = []
    
    def __init__(self):
        Algorithm.__init__(self)
        # 不创建字段描述图表
        self.will_create_field_desc_chart = False;
    
    def setTimeAndValueFieldName(self, time_field_name, value_field_name):
        self.time_field_name = time_field_name
        self.value_field_name = value_field_name
        self.inputs = pd.Series(self.data_source[self.value_field_name].values, index=self.data_source[self.time_field_name].values)
    
    def implent(self):
        # 执行算法
        pass
    
    def checkAdfAndWn(self):
        # 平稳性及白噪声检测
        new_inputs = None
        _tiltes = ["原始时序图", "一阶差分时序图", "二阶差分时序图", "三阶差分时序图"]
        for i in range(0, 4):
            if i == 0:
                # 不做差分
                new_inputs = self.inputs
            else:
                # 做i阶差分
                new_inputs = self.inputs.diff(i).dropna()
            # 平稳性
            self.adf_check_result.append(ADF(new_inputs))
            # 白噪声
            self.wn_check_result.append(acorr_ljungbox(new_inputs, lags=1))
            # 保存序列图
            fig = plt.figure()
            ax = fig.add_subplot(111)
            ax.plot(new_inputs)
            ax.set_xlabel(self.time_field_name)
            ax.set_ylabel(self.value_field_name)
            ax.set_title(_tiltes[i])
            fig.savefig("%s/ts_%d.png" % (self.chart_path, i))
    
    def prepareIpynbItems(self):
        Algorithm.prepareIpynbItems(self)
        self.ipynb_items["#time_field_name#"] = self.time_field_name
        self.ipynb_items["#value_field_name#"] = self.value_field_name
        self.ipynb_items["#forcast_period_cnt#"] = self.forcast_period_cnt
        self.ipynb_items["#diff_degrees#"] = self.diff_degrees
    
